const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
const yaml = require('yamljs');

const init = async () => {
  const sessionRes = await fetch('https://appgwbeta.test.ess.tencent.cn/consoleapp/?X-Action=CreateSession', {
    method: 'POST',
    headers: {
      'x-action': 'CreateSession',
      'Content-Type': 'application/json',
      referer: 'https://test.qian.tencent.cn/developers',
    },
    body: JSON.stringify({
      Action: 'CreateSession',
      Code: '',
      CodeType: 'NONE',
    }),
  });
  const session = await sessionRes.json();
  console.log('🚀 ~ file: init.js:18 ~ init ~ session:', session);
  const callbackUrl = await getStudioPreviewUrl();
  console.log('🚀 ~ callbackUrl: ', callbackUrl);
  if(!callbackUrl)console.error('回调地址生成失败')
  if (session.Response?.SessionId && callbackUrl) {
    const sessionId = session.Response.SessionId;
    const res = await fetch('https://appgwbeta.test.ess.tencent.cn/consoleapp/?X-Action=CreateDevelopmentApplication', {
      method: 'POST',
      headers: {
        authorization: `SessionId=${sessionId}`,
        'x-action': 'CreateDevelopmentApplication',
        'Content-Type': 'application/json',
        referer: 'https://test.qian.tencent.cn/developers',
      },
      body: JSON.stringify({
        Type: 0,
        CallbackUrl: callbackUrl,
      }),
    });
    const data = await res.json();
    console.log('🚀 ~ file: init.js:35 ~ init ~ data:', data);
    const map = data.Response;
    const envFileContent = Object.entries(map).map(([key, val]) => `X_ESS_${key.toUpperCase()}='${val}'`)
      .join('\n');

    fs.writeFileSync(path.resolve(process.cwd(), '.env.ess'), envFileContent, 'utf-8');
  }
};

// 获取预览地址
const getStudioPreviewUrl = async () =>{
  try {
    const {X_IDE_ACCESS_TOKEN, X_IDE_SPACE_KEY} = process.env;
    const res =  await fetch(`https://ide.cloud.tencent.com/api/plugin/get-access-url-token?spaceKey=${X_IDE_SPACE_KEY}`, {
      method: 'GET',
      headers: {
        'X-IDE-PLUGIN-ACCESS-TOKEN': X_IDE_ACCESS_TOKEN,
        'Content-Type': 'application/json'
      },
    });
    const data = await res.json();
    const { token, domain} = data.data;
    const previewYml =  yaml.load('.vscode/preview.yml')
    const port = previewYml.apps[0].port;
    return `https://${X_IDE_SPACE_KEY}-${token}-${port}.${domain}/api/common/callback`
  } catch (error) {
    console.error(error);
    return ''
  }
}

init();

